/**
 * @description 申请开通频道
 *
 */
seajs.use(['jquery','cookie','ajaxfileupload'], function($,cookie,$$) {
	var index = {
		init:function(){
			// mui.init({
      //     swipeBack: true //启用右滑关闭功能
      // });
			this.bucketName = 'common';
			this.domain = '';
			this.qiniuToken = '';
			this.imgPreview = $('<div class="upload-item">'+
				'<img src="" class="faceImg" />'+
				'<input id="file" name="file" type="file" style="display:block;height:70px;width:70px;opacity:0;position:absolute;padding:0;top:0;" />'+
			'</div>');
			this.imgPreview2 = $('<div class="upload-item upload-item-license">'+
				'<img src="" class="faceImg" />'+
				'<input id="file2" name="file" type="file" style="display:block;height:164px;width:164px;opacity:0;position:absolute;padding:0;top:0;" />'+
			'</div>');
			this.cookie = new cookie();
			this.userinfo = {};
			this.address = {};
			this.industry = {};
			this.provinceName = this.GetQueryString('provinceName');
			this.cityName = this.GetQueryString('cityName');
			this.areaName = this.GetQueryString('areaName');
			this.localtionLon = this.GetQueryString('localtionLon');
			this.localtionLat = this.GetQueryString('localtionLat');
			this.lat = this.GetQueryString('localtionLat');
			this.lon = this.GetQueryString('localtionLon');
			this.channelToken = this.GetQueryString('CHANNEL_TOKEN');
			this.address = '';
			this.keyword = '';
			// this.login();
			// this.initMap();
			// alert(this.localtionLon);
			// alert(this.localtionLat);
			this.cookie.setCookie('CHANNEL_TOKEN',this.channelToken);
			this.addressinit();
			this.industryinit();
			this.bindEvent();
			console.log(this.provinceName,111111);
		},
		GetQueryString:function(name){
	     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	     var r = decodeURI(window.location.search).substr(1).match(reg);
	     if(r!=null)return  unescape(r[2]); return null;
	 	},
		login:function(){
			var self = this;
			var params = {
				userAccount:'15298375152',
				userPwd:'111111',
				terminalType:1,
				deviceNumber:'KJDSLFJOIDSF-SDFJKJ-111111'
			};
			$.ajax({
				url:seajs.host+'/login',
				type:'post',
				dataType:'json',
				contentType:"application/json",
				// xhrFields:{
				// 	withCredentials:true,
				// },
				// crossDomain:true,
				data:JSON.stringify(params),
				success:function(data){
					console.log(data,99999);
					if(data.success){
						self.userinfo = data.data;
						self.cookie.setCookie('CHANNEL_TOKEN',data.data.accessToken);
						self.addressinit();
						self.industryinit();
					}else{
						alert('请求异常');
					}
				}
			});
		},
		initMap:function(){
			var self = this;
			window.initialize = function(){
				self.map = new window.BMap.Map("bigmap");            // 创建Map实例
				self.map.centerAndZoom(new window.BMap.Point(self.localtionLon, self.localtionLat), 11);
				// self.map.disableDragging();
				var local = new window.BMap.LocalSearch(self.map, {
					renderOptions: {map: self.map},
					onSearchComplete:function(data){
						console.log(data,99999);
						$('#r-result ul').empty();
						$.each(data.vr,function(i,n){
							var li = $('<li>'+
								'<div class="r-item">'+
									'<div class="r-left">'+
										'<div class="r-title">'+
											n.title+
										'</div>'+
										'<div class="r-desc">'+
											n.address+
										'</div>'+
									'</div>'+
									'<div class="r-right">'+
										'<span class="icon i-ok"></span>'+
									'</div>'+
								'</div>'+
							'</li>');
							li.click(function(e){
								li.parents('ul').find('.i-ok').removeClass('select');
								li.find('.i-ok').addClass('select');
								self.lon = n.point.lng;
								self.lat = n.point.lat;
								$('#locationLon').val(n.point.lng);
								$('#locationLat').val(n.point.lat);
								self.address = n.address;
								$('#confirmloc').removeClass('gray');
							});
							$('#r-result ul').append(li);
						})
					}
				});
				if($.trim(self.keyword)){
					local.search(self.keyword);
				}else {
					var geoc = new window.BMap.Geocoder();
					geoc.getLocation(new window.BMap.Point(self.localtionLon, self.localtionLat), function(rs){
						console.log(rs,988898);
						local.search(rs.addressComponents.street);
					});
				}

				$('#keyword').bind('input',function(e){
					console.log(1111);
					local.search($(this).val());
				});
			}
			function loadScript() {
			  var script = document.createElement("script");
			  script.src = "http://api.map.baidu.com/api?v=2.0&ak=gWUgzfPib0vllGaS7qILPisD&callback=initialize";//此为v2.0版本的引用方式
			  // http://api.map.baidu.com/api?v=1.4&ak=您的密钥&callback=initialize"; //此为v1.4版本及以前版本的引用方式
			  document.body.appendChild(script);
			}

			loadScript();
		},
		industryinit:function(){
			// 初始化行业数据
			var self = this;
			var params = {
			};
			$.ajax({
				url:seajs.host+'/apply/queryIndustry',
				type:'post',
				dataType:'json',
				contentType:"application/json",
				// xhrFields:{
				// 	withCredentials:true,
				// },
				// crossDomain:true,
				data:JSON.stringify(params),
				success:function(data){
					console.log(data,99999);
					if(data.success){
						self.industry = data.data;

						(function($, doc) {
							$.init();
							$.ready(function() {
								var _getParam = function(obj, param) {
									return obj[param] || '';
								};
								// 行业分类
								var cityPicker2 = new $.PopPicker({
									layer: 3
								});
								console.log(self.industry,88888);
								cityPicker2.setData(self.industry);
								var showCityPickerButton = doc.getElementById('showCityPicker2');
								var cityResult2 = doc.getElementById('industry');
								showCityPickerButton.addEventListener('tap', function(event) {
									doc.getElementById('channelName').blur();
									cityPicker2.show(function(items) {
										cityResult2.innerText = /*"你选择的行业分类:" +*/_getParam(items[0], 'name') + " " + _getParam(items[1], 'name') + " " + _getParam(items[2], 'name');
										doc.getElementById('firstIndustryId').value = _getParam(items[0], 'code');
										doc.getElementById('secondIndustryId').value = _getParam(items[1], 'code');
										doc.getElementById('thirdIndustryId').value = _getParam(items[2], 'code');

										//返回 false 可以阻止选择框的关闭
										//return false;
									});
								}, false);
							});
						})(window.mui, window.document);
					}else{
						alert('请求异常');
					}
				}
			});
		},
		addressinit:function(){
			// 初始化地址数据
			var self = this;
			var params = {
			};
			$.ajax({
				url:seajs.host+'/apply/queryCity',
				type:'post',
				dataType:'json',
				contentType:"application/json",
				// xhrFields:{
				// 	withCredentials:true,
				// },
				// crossDomain:true,
				data:JSON.stringify(params),
				success:function(data){
					console.log(data,99999);
					if(data.success){
						self.address = data.data;
						(function($, doc) {
							$.init();
							$.ready(function() {
								var _getParam = function(obj, param) {
									return obj[param] || '';
								};

								// 城市列表
								var cityPicker = new $.PopPicker({
									layer: 3
								});
								cityPicker.setData(self.address);
								cityPicker.pickers[0].setSelectedText(self.provinceName, 0,function(){
									cityPicker.pickers[1].setSelectedText(self.cityName, 0,function(){
										cityPicker.pickers[2].setSelectedText(self.areaName, 0);
									});
								});


								var showCityPickerButton = doc.getElementById('showCityPicker');
								var cityResult = doc.getElementById('cityResult');
								showCityPickerButton.addEventListener('tap', function(event) {
									cityPicker.show(function(items) {
										cityResult.innerText = /*"你选择的城市列表:" +*/_getParam(items[0], 'name') + " " + _getParam(items[1], 'name') + " " + _getParam(items[2], 'name');
										doc.getElementById('provinceCode').value = _getParam(items[0], 'code');
										doc.getElementById('cityCode').value = _getParam(items[1], 'code');
										doc.getElementById('areaCode').value = _getParam(items[2], 'code');
										//返回 false 可以阻止选择框的关闭
										//return false;
									});
								}, false);
							});
						})(window.mui, window.document);
					}else{
						alert('请求异常');
					}
				}
			});
		},
		bindEvent:function(){
			var self = this;

			$('#goBackTip').click(function(e){
				$('.mask').show();
				$('#confirmDialog').show();
			});

			$('#c-cancel').click(function(e){
				$('.mask').hide();
				$('#confirmDialog').hide();
			});

			$('#c-ok').click(function(e){
				window.history.go(-1);
			});

			$('#d-ok').click(function(e){
				$('.mask').hide();
				$('#alertDialog').hide();
			});

			$('#t-ok').click(function(e){
				$('.mask').hide();
				$('#TipDialog').hide();
			});

			// 修改地图定位
			$('#modify').click(function(e){
				$('#loc').show();
				self.keyword = $('#cityResult').text()+' '+$('#channelAddress').val();
				if(!self.map){
					self.initMap();
				}
			});

			$('#confirmloc').click(function(e){
				if($(this).hasClass('gray')){
					return false;
				}
				self.localtionLon = self.lon;
				self.localtionLat = self.lat;
				$('#loc').hide();
				$('.modifyBtn').show();
				$('.map-tips').hide();
				$('.mapArea').show();
				$('.mapArea-text').text(self.address);
				var map = new window.BMap.Map("allmap");            // 创建Map实例
				map.centerAndZoom(new window.BMap.Point(self.localtionLon, self.localtionLat), 11);
				map.disableDragging();
				var point = new window.BMap.Point(self.localtionLon, self.localtionLat);
				var marker = new window.BMap.Marker(point);
				map.addOverlay(marker);
			});

			$('#goback').click(function(e){
				$('#loc').hide();
			});
			// 申请开通
			$('#apply').click(function(e){
				var params = {
					channelImg:$('#channelImg').val(),
					channelName:$('#channelName').val(),
					firstIndustryId:$('#firstIndustryId').val(),
					secondIndustryId:$('#secondIndustryId').val(),
					thirdIndustryId:$('#thirdIndustryId').val(),
					provinceCode:$('#provinceCode').val(),
					cityCode:$('#cityCode').val(),
					areaCode:$('#areaCode').val(),
					channelAddress:$('#channelAddress').val(),
					locationLon:$('#locationLon').val()?$('#locationLon').val():self.localtionLon,
					locationLat:$('#locationLat').val()?$('#locationLat').val():self.localtionLat,
					legalPersonName:$('#legalPersonName').val(),
					linkmanMobilePhone:$('#linkmanMobilePhone').val(),
					companyYYZZImg:$('#companyYYZZImg').val(),
					linkmanAccountId:self.GetQueryString('linkmanAccountId')?self.GetQueryString('linkmanAccountId'):1000016
				};
				if(!self.varify(params)){
					return false;
				}
				$.ajax({
					url:seajs.host+'/apply/applyChannel',
					type:'POST',
					dataType:'json',
					contentType:"application/json",
					data:JSON.stringify(params),
					success:function(data){
						// console.debug(data,99999);
						if(data.success){
							self.needPay = data.data.needPay;
							self.orderCode = data.data.orderCode;
							// 弹出弹层
							$('.mask').show();
							$('#alertDialog').show();
						}else{
							alert('请求异常');
						}
					}
				});
			});


			// 上传图片
			// if($.os.android && $('#fromApp').val()==1){
			// 		$('body').delegate('#file','click',function(e) {
			// 				var param = {
			// 						'bucketName':self.bucketName,
			// 						'cb':'ImageUploaded'
			// 				}
			// 				window.aijia.uploadFile(JSON.stringify(param));
			//
			// 		})
			// 		window.ImageUploaded = function(url){
			// 				var preview = self.imgPreview.clone();
			// 				// preview.find('.faceImg').attr('src',url);
			// 				// $('#file').parents('li').before(preview);
			// 		}
			// }else{
					self.count = -1;
					$('body').delegate('#file','change',function(e) {
							self.count++;
							var file = this;
							var filetypes = /jpg|jpeg|png|gif|bmp|tiff/;
							var filemaxsize = 1024*4;//4M
							if(file.files[0].size/1024>filemaxsize){
								// 提示文件太大
								// console.log(window.mui,999999);
								window.mui.alert('文件太大', '提示', function() {
                });
								return false;
							}
							// alert(file.files[0].name);
							if(!file.files[0].name.toLowerCase().match(filetypes)){
								window.mui.alert('应上传图片', '提示', function() {
                });
								return false;
							}
							// 先获得token
							$.ajax({
									 url: seajs.host+'/getQiniuToken'+'?bucketName='+self.bucketName,
									type: 'GET',
									dataType: 'json',
									data: {},
									success:function(data){
											if(data.success){
												var token = '';
												var domain = '';
												$.each(data.data,function(i,n){
													if(n.bucketName == 'common'){
														token = n.qiniuToken;
														domain = n.bucketUrl;
													}
												})
													self.token = token;
													self.domain = domain;
													self.key = new Date().getTime();
													var formData = new FormData();
													formData.append("token", token);
													formData.append("file", file.files[0]);
													formData.append("accept", "text/plain");
													if (true) {
														//timestamp如果为true，文件名增加时间戳，同一个文件可传多次
														//如果为false，默认hash为key，同一个文件不可传多次
														var fileName = file.files[0].name;
														var curTimestamp = new Date().getTime();
														formData.append("key", curTimestamp + '-' + fileName);
													}
													$.ajax({
														url: 'http://upload.qiniu.com',
														type: 'POST',
														dataType: 'json',
														data: formData,
														processData: false,
														contentType: false,
														success: function(data) {
															// deferred.resolve('http://' + domain + '/' + data.key);
															//预览图片
															console.debug(data,22222);
															var url = 'http://'+self.domain+'/'+data.key+'?imageView2/1/w/70/h/70';
															var preview = self.imgPreview.clone();
															preview.find('.faceImg').attr('src',url);
															$('#fengmian .upload-item').remove();
															$('#fengmian').prepend(preview);
															$('#channelImg').val(url);

														},
														error: function() {
															// console.debug('请检查网络');
														},
														complete: function() {
															// blockUI.unblock()
														}
													});
													$("#file").replaceWith('<input id="file" name="file" type="file" style="display:block;height:70px;width:70px;opacity:0;position:absolute;padding:0;top:0;" title='+self.count+' />');
											}
									},
									error:function(xhr, data, status){

									}
							});
					});

					self.count2 = -1;
					$('body').delegate('#file2','change',function(e) {
							self.count2++;
							var file = this;
							// 先获得token
							$.ajax({
									 url: seajs.host+'/getQiniuToken'+'?bucketName='+self.bucketName,
									type: 'GET',
									dataType: 'json',
									data: {},
									success:function(data){
											if(data.success){
												var token = '';
												var domain = '';
												$.each(data.data,function(i,n){
													if(n.bucketName == 'common'){
														token = n.qiniuToken;
														domain = n.bucketUrl;
													}
												})
													self.token = token;
													self.domain = domain;
													self.key = new Date().getTime();
													var formData = new FormData();
													formData.append("token", token);
													formData.append("file", file.files[0]);
													formData.append("accept", "text/plain");
													if (true) {
														//timestamp如果为true，文件名增加时间戳，同一个文件可传多次
														//如果为false，默认hash为key，同一个文件不可传多次
														var fileName = file.files[0].name;
														var curTimestamp = new Date().getTime();
														formData.append("key", curTimestamp + '-' + fileName);
													}
													$.ajax({
														url: 'http://upload.qiniu.com',
														type: 'POST',
														dataType: 'json',
														data: formData,
														processData: false,
														contentType: false,
														success: function(data) {
															// deferred.resolve('http://' + domain + '/' + data.key);
															//预览图片
															console.debug(data,22222);
															var url = 'http://'+self.domain+'/'+data.key+'?imageView2/1/w/164/h/164';
															var preview = self.imgPreview2.clone();
															preview.find('.faceImg').attr('src',url);
															$('#zhizhao .upload-item').remove();
															$('#zhizhao').prepend(preview);
															$('#companyYYZZImg').val(url);
														},
														error: function() {
															// console.debug('请检查网络');
														},
														complete: function() {
															// blockUI.unblock()
														}
													});
													$("#file2").replaceWith('<input id="file2" name="file" type="file" style="display:block;height:164px;width:164px;opacity:0;position:absolute;padding:0;top:0;" title='+self.count2+' />');
											}
									},
									error:function(xhr, data, status){

									}
							});
					});
			// }
		},
		varify:function(params){
			var self = this;
			var flag = false;
			//channelImg:$('#channelImg').val(),
			// channelName:$('#channelName').val(),
			// firstIndustryId:$('#firstIndustryId').val(),
			// secondIndustryId:$('#secondIndustryId').val(),
			// thirdIndustryId:$('#thirdIndustryId').val(),
			// provinceCode:$('#provinceCode').val(),
			// cityCode:$('#cityCode').val(),
			// areaCode:$('#areaCode').val(),
			// channelAddress:$('#channelAddress').val(),
			// locationLon:$('#locationLon').val()?$('#locationLon').val():self.localtionLon,
			// locationLat:$('#locationLat').val()?$('#locationLat').val():self.locationLat,
			// legalPersonName:$('#legalPersonName').val(),
			// linkmanMobilePhone:$('#linkmanMobilePhone').val(),
			// companyYYZZImg:$('#companyYYZZImg').val(),
			// linkmanAccountId
			if(params.channelImg && params.channelName && params.firstIndustryId && params.provinceCode && params.cityCode && params.areaCode && params.channelAddress && params.locationLon && params.locationLat && params.legalPersonName && params.linkmanMobilePhone && params.linkmanAccountId){
				var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
				if(myreg.test(params.linkmanMobilePhone)){
					flag = true;
				}else{
					window.mui.alert('请填写正确的手机号', '提示', function() {
					});
				}

			}else{
				$('.mask').show();
				$('#TipDialog').show();
			}
			return flag;
		}
	}
	index.init();
});
